package com.camemax.controller;

import com.camemax.operators.LoginFailedProcess;
import com.camemax.pojo.LoginEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.net.URL;
import java.time.Duration;

public class LoginFailedDetect {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        URL resource = LoginFailedDetect.class.getResource("/LoginLog.csv");
        env.readTextFile(resource.getPath())
            .map( line -> {
                String[] fields = line.split(",");
                return new LoginEvent(
                        Long.valueOf(fields[0]),
                        fields[1],
                        fields[2],
                        Long.parseLong(fields[3])
                );
            })
            .assignTimestampsAndWatermarks(WatermarkStrategy.<LoginEvent>forBoundedOutOfOrderness(Duration.ofSeconds(10))
            .withTimestampAssigner((SerializableTimestampAssigner<LoginEvent>) ( pojo, defaultTime) -> pojo.getLoginDate() * 1000L))
            .keyBy(LoginEvent::getUserId)
            .process(new LoginFailedProcess(3))
                .print();

        env.execute("Login Failed Detect Job");
    }
}
